package com.waterflow.xanner.model;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.waterflow.xanner.model.LevelManager.LevelInfo;

public class PlayerProgress {
	private int current_level;
	private int lastSolved;
	private LevelManager levelManager;

	private static final String PREFERENCES_NAME = "player_progress";
	private static final String KEY_CURRENT_LEVEL = "key_curent_level";
	private static final String KEY_LAST_SOLVED = "key_last_solved";

	public PlayerProgress(Context context) {
		levelManager = new LevelManager(context);
		current_level = 0;
		lastSolved = -1;
	}

	public boolean canGoToNextLevel() {
		return (current_level <= lastSolved)
				&& levelManager.hasLevel(current_level + 1);
	}

	public boolean canGoToPreviousLevel() {
		return levelManager.hasLevel(current_level - 1);
	}

	public LevelInfo currentLevel() {
		return levelManager.get(current_level);
	}

	public int currentLevelIndex() {
		return current_level;
	}

	public void nextLevel() {
		if (!canGoToNextLevel()) {
			throw new RuntimeException();
		}
		current_level++;
	}

	public void previousLevel() {
		if (!canGoToPreviousLevel()) {
			throw new RuntimeException();
		}
		current_level--;
	}

	public boolean trySolution(String answer) {
		if (levelManager.isSolution(current_level, answer)) {
			lastSolved = Math.max(lastSolved, current_level);
			return true;
		}
		return false;
	}

	public void saveProgress(Context context) {
		SharedPreferences prefs = context.getSharedPreferences(
				PREFERENCES_NAME, Context.MODE_PRIVATE);
		Editor edit = prefs.edit();
		edit.putInt(KEY_CURRENT_LEVEL, current_level);
		edit.putInt(KEY_LAST_SOLVED, lastSolved);
		
		edit.apply();
	}
	
	public void loadProgress(Context context) {
		SharedPreferences prefs = context.getSharedPreferences(
				PREFERENCES_NAME, Context.MODE_PRIVATE);
		current_level = prefs.getInt(KEY_CURRENT_LEVEL, 0);
		lastSolved = prefs.getInt(KEY_LAST_SOLVED, -1);
	}
	
	public boolean finishedFirstLevel(){
		return lastSolved > -1;
	}
}
